import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:kasax_demos2/commons/config_common.dart';
import 'package:kasax_demos2/entry/entrys.dart';
import 'package:kasax_demos2/entry/movie_new_info_entity.dart';
import 'package:kasax_demos2/entry/user_info_response_entity.dart';
import 'package:kasax_demos2/gankio/entry/girl_category_result_entity.dart';
import 'package:kasax_demos2/gankio/entry/girl_sub_category_result_entity.dart';
import 'package:kasax_demos2/generated/json/girl_category_result_entity_helper.dart';
import 'package:kasax_demos2/generated/json/girl_sub_category_result_entity_helper.dart';
import 'package:kasax_demos2/generated/json/movie_new_info_entity_helper.dart';
import 'package:dio/adapter.dart';
import 'package:kasax_demos2/generated/json/user_info_response_entity_helper.dart';
import 'package:kasax_demos2/meiyingfilm/entry/film_response.dart';
import 'package:kasax_demos2/testhelper/gankio/entry_banner.dart';

class DioManager {
  static final DioManager _instance = DioManager._internal();
  var TIME_OUT_DURATION = 50 * 1000;

  factory DioManager() => _instance;

  late Dio _dio;
  String currentBaseUrl = AppConsts.POSTS_URL_BASEURL;

  DioManager._internal() {
    _initDio();
  }

  static DioManager getInstance() {
    return _instance;
  }

  void _initDio() {
    currentBaseUrl = AppConsts.POSTS_URL_BASEURL;
    initDio();
  }

  void initDio() {
    var options = BaseOptions(
        baseUrl: currentBaseUrl,
        connectTimeout: TIME_OUT_DURATION,
        receiveTimeout: TIME_OUT_DURATION);
    _dio = Dio(options);
  }

  Future<List<Posts>> fetchPostsList() async {
    var response = await _dio.get(AppConsts.POSTS_URL_PATH);
    List<Posts> posts = <Posts>[];
    if (response.statusCode == 200) {
      posts = response.data['posts']
          .map<Posts>((item) => Posts.fromJson(item))
          .toList();
    }
    return posts;
  }

  /// 数据转换工具使用:JsonToDartBeanAction
  Future<FilmResponse> fetchMovieList(
      String path, int page, int pageSize) async {
    log("fetchMovieList: $path , $page , $pageSize");
    if (currentBaseUrl != AppConsts.MOVIE_BASEURL) {
      currentBaseUrl = AppConsts.MOVIE_BASEURL;
      initDio();
    }
    int offset = (page - 1) * pageSize;
    var queryPath = "$path?start=$offset&count=$pageSize";
    log("queryPath: $queryPath");
    var response = await _dio.get(queryPath);
    // var entry = MovieNewInfoEntity();
    FilmResponse result = FilmResponse();
    try {
      if (response.statusCode == 200) {
        var data = response.data;
        // movieNewInfoEntityFromJson(entry, data);
        result = FilmResponse.fromJson(data);
      }
    } catch (e) {
      log("error:${e}");
    }
    return result;
  }

  /// 获取banners
  /// 首页banner轮播
  Future<List<BannerItem>> fetchBanners() async {
    // https://gank.io/api/v2/banners
    configGankioDio();

    var response = await _dio.get("banners");
    List<BannerItem> banners = <BannerItem>[];
    try {
      if (response.statusCode == 200) {
        var data = response.data;
        banners = data.map<BannerItem>((e) {
          return BannerItem.fromJson(e);
        }).toList();
      }
    } catch (e) {
      log("error:${e}");
    }
    return banners;
  }

  /// 分类 API
  /// 参数： category_type 可接受参数 Article | GanHuo | Girl
  // Article: 专题分类、 GanHuo: 干货分类 、 Girl:妹子图
  /// 获取干货所有子分类
  //    https://gank.io/api/v2/categories/GanHuo
  //    获取文章所有子分类
  //    https://gank.io/api/v2/categories/Article
  //    获取妹纸所有子分类
  //    https://gank.io/api/v2/categories/Girl
  //    妹子图类型只有一项: 且为Girl
  Future<GirlCategoryResultEntity> featCategories(String category_type) async {
    configGankioDio();
    GirlCategoryResultEntity resultEntity = GirlCategoryResultEntity();
    try {
      var response = await _dio.get("categories/$category_type");
      if (response.statusCode == 200) {
        girlCategoryResultEntityFromJson(resultEntity, response.data);
      }
      log("featCategories resultEntity: $resultEntity");
    } catch (e) {
      log("featCategories error: $e");
    }
    return resultEntity;
  }

  /// 配置gankio
  /// 强制去除证书校验
  void configGankioDio() {
    if (currentBaseUrl != AppConsts.GANKIO_BASEURL) {
      currentBaseUrl = AppConsts.GANKIO_BASEURL;
      initDio();
      // 强制去除证书校验，需要import 'package:dio/adapter.dart';
      (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
          (client) {
        client.badCertificateCallback = (cert, host, port) {
          return true;
        };
      };
    }
  }

  /// 分类数据 API
  /// category 可接受参数 All(所有分类) | Article | GanHuo | Girl
  // type 可接受参数 All(全部类型) | Android | iOS | Flutter | Girl ...，即分类API返回的类型数据
  // count: [10, 50]
  // page: >=1
  ///  获取妹子列表
  ///  https://gank.io/api/v2/data/category/Girl/type/Girl/page/1/count/10
  ///  获取Android干货列表
  ///  https://gank.io/api/v2/data/category/GanHuo/type/Android/page/1/count/10
  Future<GirlSubCategoryResultEntity> featBatchCategory(
      String category, String type, int page, int count) async {
    configGankioDio();
    GirlSubCategoryResultEntity resultEntity = GirlSubCategoryResultEntity();
    try {
      var response = await _dio
          .get("data/category/$category/type/$type/page/$page/count/$count");
      if (response.statusCode == 200) {
        girlSubCategoryResultEntityFromJson(resultEntity, response.data);
      }
      log("featBatchCategory resultEntity: $resultEntity");
    } catch (e) {
      log("featBatchCategory error: $e");
    }
    return resultEntity;
  }

  /// 随机 API
  /// 获取干货分类下Android子分类的10个随机文章列表
  // https://gank.io/api/v2/random/category/GanHuo/type/Android/count/10
  Future featRandomCategory(
      String category, String type, int page, int count) async {
    configGankioDio();
    var response = await _dio
        .get("random/category/$category/type/$type/page/$page/count/$count");
  }

  /// 文章详情 API
  /// 获取5e777432b8ea09cade05263f的详情数据
  // https://gank.io/api/v2/post/5e777432b8ea09cade05263f
  Future featPost(String post_id) async {
    configGankioDio();
    var response = await _dio.get("post/$post_id");
  }

  /// 本周最热 API
  /// hot_type 可接受参数 views（浏览数） | likes（点赞数） | comments（评论数）❌
  // category 可接受参数 Article | GanHuo | Girl
  // count: [1, 20]
  Future featHot(String hot_type, String category, int count) async {
    configGankioDio();
    var response =
        await _dio.get("hot/$hot_type/category/$category/count/$count");
  }

  /// 文章评论获取 API
  Future featComments(String post_id) async {
    configGankioDio();
    var response = await _dio.get("post/comments/$post_id");
  }

  /// 搜索 API
  /// search 可接受参数 要搜索的内容
  // category 可接受参数 All[所有分类] | Article | GanHuo
  // type 可接受参数 Android | iOS | Flutter ...，即分类API返回的类型数据
  // count: [10, 50]
  // page: >=1
  /// 搜索干货-Android分类下的Android关键字 https://gank.io/api/v2/search/android/category/GanHuo/type/Android/page/1/count/10
  // 搜索文章-Android分类下的Android关键字 https://gank.io/api/v2/search/android/category/Article/type/Android/page/1/count/10
  // 搜索全部分类下的Android关键字 https://gank.io/api/v2/search/android/category/All/type/All/page/1/count/10
  Future search(
      String search, String category, String type, int page, int count) async {
    configGankioDio();
    var response = await _dio.get(
        "search/$search/category/$category/type/$type/page/$page/count/$count");
  }

  Future<UserInfoResponseEntity> fetchAllUser() async {
    currentBaseUrl = AppConsts.REQRES_IN_API_BASEURL;
    initDio();

    UserInfoResponseEntity resultEntity = UserInfoResponseEntity();
    try {
      var response = await _dio.get("users?per_page=20");
      if (response.statusCode == 200) {
        userInfoResponseEntityFromJson(resultEntity, response.data);
      }
      log("fetchAllUser resultEntity: $resultEntity");
    } catch (e) {
      log("fetchAllUser error: $e");
    }
    return resultEntity;
  }
}
